package nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author Summerday
 */
public class Server {

    public static void main(String[] args) throws IOException {
        // 开启服务器端的通道
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 监听端口号
        ssc.bind(new InetSocketAddress(8081));
        // 手动设置为非阻塞模式
        ssc.configureBlocking(false);
        // 接收连接
        SocketChannel sc = ssc.accept();
        // 保证连接
        while (sc == null) {
            sc = ssc.accept();
        }
        // 读取数据
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        sc.read(buffer);
        byte[] bs = buffer.array();
        System.out.println(new String(bs, 0, buffer.position()));

        sc.write(ByteBuffer.wrap("hello client! i am server !".getBytes()));
        // 关流
        ssc.close();

    }
}
